﻿using GamFi.API.Application.Interfaces;
using GamFi.API.Domain.Entities;
using Microsoft.Extensions.Logging;
using MongoDB.Bson;
using MongoDB.Driver;

namespace GamFi.API.Infrastructure.Services;

public class CleanupService(IMongoDatabase database, ILogger<CleanupService> logger) : ICleanupService
{
    private const int MaxMessages = 1000;

    public async Task RemoveOldMessagesAsync(CancellationToken cancellationToken)
    {
        var messagesCollection = database.GetCollection<Message>("Messages");

        var totalMessages = await messagesCollection.CountDocumentsAsync(new BsonDocument(), cancellationToken: cancellationToken);
        if (totalMessages > MaxMessages)
        {
            var oldestMessages = await messagesCollection.Find(new BsonDocument())
                .SortBy(m => m.CreatedDate)
                .Limit((int)(totalMessages - MaxMessages))
                .ToListAsync(cancellationToken);

            var oldestMessageIds = oldestMessages.Select(m => m.Id).ToList();

            var filter = Builders<Message>.Filter.In(m => m.Id, oldestMessageIds);
            await messagesCollection.DeleteManyAsync(filter, cancellationToken);

            logger.LogInformation($"{oldestMessages.Count} old messages were removed.");
        }
    }
}